package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.lsh.base.http.client.core.HttpClient;
import com.lsh.oms.api.model.status.MisArrivalDto;
import com.lsh.oms.core.constant.OtherSystemConstant;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.model.order.OrderShippingHead;
import com.lsh.oms.core.service.tool.ToolService;
import com.lsh.oms.core.utils.HttpUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lsh.base.http.client.ResponseAssertions.success;

/**
 * @author panxudong
 * @date 16/12/20
 */
@Component
public class TmsProxy extends BaseProxy {

    private static Logger logger = LoggerFactory.getLogger(TmsProxy.class);

    private static final String CHANGE_DELIVERY_TIME_URL = "/order/order/ChangeDeliveryTimeMemo";

    private static final String CHANGE_TRANS_LIMIT_URL = "/order/order/ChangeTransLimit";

    private static final String CHANGE_SHIPPED_TASK = "/collect/task/shipped";

    private static final String CHANGE_TASK_CANCEL = "/collect/task/cancel";

    private static final String CREATE_TASK = "/collect/task/addTask";

    private static final String TERMINATE_TASK = "/collect/task/finished";

    private static final String BILL_TRAN_INFO = "/bill/Warehouse/getTransUserByUids";

    @Value("${tms.host}")
    private String tmsHost;

    @Resource(name = "apache.http.client")
    protected HttpClient https;

    public Map<String, Object> createTask(Map<String, Object> request) {
        Map<String, Object> response = https.postFrom(tmsHost + CREATE_TASK, request);
        if (!success(response)) {
            throw BusinessException.badRequest("TMS任务创建失败");
        }
        return response;
    }

    public Map<String, Object> cancelTask(Map<String, Object> request) {
        Map<String, Object> response = https.postFrom(tmsHost + CHANGE_TASK_CANCEL, request);
        if (!success(response)) {
            throw BusinessException.badRequest("TMS任务取消失败");
        }
        return response;
    }

    public Map<String, Object> terminateTask(Map<String, Object> request) {
        Map<String, Object> response = https.postFrom(tmsHost + TERMINATE_TASK, request);
        if (!success(response)) {
            throw BusinessException.badRequest("TMS任务结束失败");
        }
        return response;
    }

    public HttpMessage shippedTask(String uuid, OrderShippingHead orderShippingHead, Long venderId) throws IOException {
        String url = tmsHost + CHANGE_SHIPPED_TASK;
        Map<String, Object> params = new HashMap<>(8);
        params.put("warehouse_id", orderShippingHead.getWarehouseId());
        params.put("other_id", orderShippingHead.getOrderId());
        params.put("type", orderShippingHead.getOrderFrom());
        params.put("lack_flag", orderShippingHead.getLackFlag());

        String message = "[TmsProxy][collect task shipped][" + uuid + "]";
        return super.sendPostRequest(message, ToolService.getRequestTmsHeader(uuid, venderId), url, params);
    }

    public HttpMessage getTranInfo(String uuid, Long uid, Long venderId) throws IOException {
        String url = tmsHost + BILL_TRAN_INFO;
        Map<String, Object> params = new HashMap<>(4);
        params.put("uids[]", uid);

        String message = "[TmsProxy][bill getTransUserByUids shipped][" + uuid + "]";
        return super.sendPostRequest(message, ToolService.getRequestTmsHeader(uuid, venderId), url, params);
    }

    public HttpMessage cancelTask(String uuid, Long orderCode, Integer type, Long venderId) throws IOException {
        String url = tmsHost + CHANGE_TASK_CANCEL;
        Map<String, Object> params = new HashMap<>(8);
        params.put("other_id", orderCode);
        params.put("type", type);

        String message = "[TmsProxy][collect task shipped][" + uuid + "]";
        return super.sendPostRequest(message, ToolService.getRequestTmsHeader(uuid, venderId), url, params);
    }

    public HttpMessage changeDeliveryTime(String uuid, long code, String deliveryTimeMemo, Long venderId) throws IOException {
        String url = tmsHost + CHANGE_DELIVERY_TIME_URL;
        Map<String, Object> params = new HashMap<>(5);
        params.put("order_id", code);
        params.put("delivery_time_memo", deliveryTimeMemo);

        String message = "[TmsProxy][Change delivery time memo][" + uuid + "]";
        return super.sendPostRequest(message, ToolService.getRequestTmsHeader(uuid, venderId), url, params);
    }

    public HttpMessage changeTransLimit(String uuid, long code, String transLimit, Long venderId) throws IOException {
        String url = tmsHost + CHANGE_TRANS_LIMIT_URL;
        Map<String, Object> params = new HashMap<>();
        params.put("order_id", code);
        params.put("trans_limit", transLimit);

        String message = "[TmsProxy][Change trans limit][" + uuid + "]";
        return super.sendPostRequest(message, ToolService.getRequestTmsHeader(uuid, venderId), url, params);
    }


    public int reqTmsReceiptConfirm(MisArrivalDto dto, String logSign) throws Throwable {
        List<BasicNameValuePair> pairs = new ArrayList<>(3);
        pairs.add(new BasicNameValuePair("receipt_order_id", dto.getReceiptOrderId()));
        if (dto.getPayType() != null) {
            pairs.add(new BasicNameValuePair("pay_type", dto.getPayType() + ""));
        }
        pairs.add(new BasicNameValuePair("mome", dto.getMemo()));
        HttpEntity param = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
        String url = tmsHost + OtherSystemConstant.TMS_RECEIPT_CONFIRM;
        logger.info(logSign + "确认到账调用tms -- url is - " + url);
        logger.info(logSign + "确认到账调用tms -- params is - " + param);
        long start = System.currentTimeMillis();
        String result = HttpUtils.post(url, param, false, this.buildHeaders(dto.getVenderId())).getData();
        logger.info(logSign + "请求tms耗时:" + (System.currentTimeMillis() - start) + "ms");
        logger.info(logSign + "确认到账调用tms返回:" + result);
        int ret = JSON.parseObject(result).getInteger("ret");
        return ret;
    }

    private Header[] buildHeaders(Long venderId) {
        Header[] headers = {new BasicHeader("api-version", "1.1"),
                new BasicHeader("platform", "oms"),
                new BasicHeader("venderId", venderId + ""),
                new BasicHeader("sign", "md5")};
        return headers;
    }

}
